<template>
  <el-dialog :title="dialogTitle" v-model="dialogVisible" style="width: 80%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="试卷" prop="paperId">
        <el-row :gutter="24">
          <el-col :span="16">
            <el-input v-model="formData.paperName" disabled/>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="openPaperListForm()"> 选择试卷</el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="考试时长" prop="duration">
            <el-row :gutter="24">
              <el-col :span="12">
                <el-input v-model="formData.duration" placeholder="请输入考试时长（分钟）"/>
              </el-col>
              <el-col :span="12">
                <span>（分钟）</span>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="总分" prop="totalScore">
            <el-input v-model="formData.totalScore" placeholder="请输入总分" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="及格分数" prop="passingScore">
            <el-input v-model="formData.passingScore" placeholder="请输入及格分数"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="考试名称" prop="examName">
        <el-input v-model="formData.examName" placeholder="请输入考试名称"/>
      </el-form-item>
      <el-row :gutter="24">
        <el-col span="12">
          <el-form-item label="考试开始时间" prop="startTime">
            <el-date-picker type="datetime"
                            value-format="x" v-model="formData.startTime" placeholder="请选择考试开始时间"/>
          </el-form-item>
        </el-col>
        <el-col span="12">
          <el-form-item label="考试结束时间" prop="endTime">
            <el-date-picker type="datetime"
                            value-format="x" v-model="formData.endTime" placeholder="请选择考试结束时间"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col span="12">
          <el-form-item label="结束设置" prop="examName">
            <el-radio-group v-model="formData.endType">
              <el-radio :label=0>及格结束</el-radio>
              <el-radio :label=1>不限次数</el-radio>
              <el-radio :label=2>限制次数</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col span="12">
          <el-form-item v-if="formData.endType === 2" label="次数设置" prop="testNum">
            <el-input-number v-model="formData.testNum"/>
          </el-form-item>

        </el-col>
      </el-row>
      <el-form-item label="成绩设置" prop="examName">
        <el-radio-group v-model="formData.scoreType">
          <el-radio :label=0>最高分</el-radio>
          <el-radio :label=1>最后一次</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-row :gutter="24">
        <div style="color: red;padding: 30px">
          <label style="font-size: large;padding-left: 20px">合计:</label>
          <el-tag v-if="formData.easyNum>0" style="color: red;margin-right: 20px;margin-left: 20px">
            简单：{{ formData.easyNum }}
          </el-tag>
          <el-tag v-if="formData.commonNum>0" style="color: red;margin-right: 20px">
            一般：{{ formData.commonNum }}
          </el-tag>
          <el-tag v-if="formData.mediumNum>0" style="color: red;margin-right: 20px">
            中等：{{ formData.mediumNum }}
          </el-tag>
          <el-tag v-if="formData.difficultNum>0" style="color: red;margin-right: 20px">
            困难：{{ formData.difficultNum }}
          </el-tag>
          <el-tag v-if="formData.extremelyDifficultNum>0" style="color: red;margin-right: 20px">
            极难：{{ formData.extremelyDifficultNum }}
          </el-tag>
        </div>
      </el-row>
      <el-row :gutter="24" v-if="formData.singleChoiceNum>0||formData.trueFalseNum>0">
        <el-col v-if="formData.singleChoiceNum>0" :span="10">
          <div>
            <el-form-item label="单选题分值" prop="singleChoiceScore">
              <el-input-number min="0" v-model="formData.singleChoiceScore" placeholder="请输入单选题数量"
                               @change="totalScore" disabled/>

              <span style="margin-left: 20px;color: red">单选总分：{{ formData.singleChoiceNum }}题 * {{
                  formData.singleChoiceScore
                }}分={{ formData.singleChoiceNum * formData.singleChoiceScore }}分</span>
            </el-form-item>
          </div>
        </el-col>
        <el-col v-if="formData.trueFalseNum>0" :span="10">
          <div>
            <el-form-item label="判断题分值" prop="trueFalseScore">
              <el-input-number min="0" v-model="formData.trueFalseScore" placeholder="请输入判断题分值"
                               @change="totalScore" disabled/>
              <span style="margin-left: 20px;color: red">判断题总分：{{ formData.trueFalseNum }}题 * {{
                  formData.trueFalseScore
                }}分={{ formData.trueFalseNum * formData.trueFalseScore }}分</span>

            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row v-if="formData.multipleChoiceNum>0" :gutter="24">
        <el-col>
          <div>
            <el-form-item label="多选题分值" prop="multipleChoiceFullScore">
              <el-input-number min="0" v-model="formData.multipleChoiceFullScore"
                               placeholder="请输入多选题分值" @change="totalScore" disabled/>
              <span style="margin-left: 20px">漏选得分<el-input-number min="0"
                                                                   v-model="formData.multipleChoicePartialScore"
                                                                   placeholder="请输入漏选分值"/></span>
              <span style="margin-left: 20px;color: red">多选题总分：{{ formData.multipleChoiceNum }}题 * {{
                  formData.multipleChoiceFullScore
                }}分={{ formData.multipleChoiceNum * formData.multipleChoiceFullScore }}分</span>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="24"
              v-if="formData.fillNum>0||formData.shortAnswerNum>0||formData.essayNum>0||formData.calculateNum>0">
        <el-col :span="6" v-if="formData.fillNum>0">
          <div>
            <el-form-item label="填空题总分" prop="fillTotalScore">
              <span
                style="margin-left: 20px;color: red">共：{{ formData.fillNum }}题 共{{ formData.fillTotalScore }}分</span>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="6" v-if="formData.shortAnswerNum>0">
          <div>
            <el-form-item label="简答题总分" prop="shortAnswerTotalScore">
              <span
                style="margin-left: 20px;color: red">共：{{ formData.shortAnswerNum }}题 共{{ formData.shortAnswerTotalScore }}分</span>
            </el-form-item>
          </div>
        </el-col>

        <el-col :span="6" v-if="formData.essayNum>0">
          <div>
            <el-form-item label="问答题总分" prop="essayTotalScore">
              <span
                style="margin-left: 20px;color: red">共：{{ formData.essayNum }}题 共{{ formData.essayTotalScore }}分</span>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="6" v-if="formData.calculateNum>0">
          <div>
            <el-form-item label="计算题总分" prop="calculateTotalScore">
              <span
                style="margin-left: 20px;color: red">共：{{ formData.calculateNum }}题 共{{ formData.calculateTotalScore }}分</span>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-form-item label="试卷类型" prop="paperType">
        <el-radio-group v-model="formData.paperType" disabled>
          <el-radio :label=0 >固定</el-radio>
          <el-radio :label=1 >随机</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="formData.paperType===1" label="出题类型" prop="testType">
        <el-radio-group v-model="formData.testType" disabled>
          <el-radio :label=0 >无</el-radio>
          <el-radio :label=1 >难易</el-radio>
          <el-radio :label=2 >知识点</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-dialog>
  <PaperList ref="paperListRef" @selectPaper="receiveDataFromPaperList"/>
</template>
<script setup lang="ts">
import {Api, VO} from '@/api/exam/exam'
import PaperList from './PaperList.vue'

/** 考试 表单 */
defineOptions({name: 'Form'})

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const paperListRef = ref()
const openPaperListForm = () => {
  paperListRef.value.open()
}
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  examName: undefined,
  paperId: undefined,
  paperName: undefined,
  duration: undefined,
  version: undefined,
  endType: 0,
  scoreType: 0,
  startTime: undefined,
  endTime: undefined,
  testNum: undefined,
  testType: undefined,
  totalScore: undefined,
  passingScore: undefined,
  scoreLine: undefined,
  singleChoiceNum: undefined,
  multipleChoiceNum: undefined,
  shortAnswerNum: undefined,
  essayNum: undefined,
  trueFalseNum: undefined,
  singleChoiceScore: undefined,
  multipleChoiceScore: undefined,
  multipleChoicePartialScore: undefined,
  shortAnswerScore: undefined,
  essayScore: undefined,
  trueFalseScore: undefined,
  singleChoiceTotalScore: undefined,
  multipleChoiceTotalScore: undefined,
  shortAnswerTotalScore: undefined,
  essayTotalScore: undefined,
  trueFalseTotalScore: undefined,
  questionType: undefined,
  questionTypeConfig: undefined,
})
const formRules = reactive({
  examName: [{required: true, message: '考试名称不能为空', trigger: 'blur'}],
  duration: [{required: true, message: '考试时长（分钟）不能为空', trigger: 'blur'}],
  passingScore: [{required: true, message: '及格分数不能为空', trigger: 'blur'}],
  startTime: [{required: true, message: '考试开始时间不能为空', trigger: 'blur'}],
  endTime: [{required: true, message: '考试结束时间不能为空', trigger: 'blur'}],
  endType: [{required: true, message: '考试结束设置不能为空', trigger: 'blur'}],
  scoreType: [{required: true, message: '考试高分设置不能为空', trigger: 'blur'}],
})
const formRef = ref() // 表单 Ref
const id = ref()
/** 打开弹窗 */
const open = async (type: string, eid?: number) => {
  id.value = eid
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (eid) {
    formLoading.value = true
    try {
      formData.value = await Api.get(eid)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({open}) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as VO
    if (formType.value === 'create') {
      await Api.create(data)
      message.success(t('common.createSuccess'))
    } else {
      await Api.update(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    examName: undefined,
    paperId: undefined,
    duration: undefined,
    version: undefined,
    endType: 0,
    scoreType: 0,
    startTime: undefined,
    endTime: undefined,
    testNum: undefined,
    testType: undefined,
    totalScore: undefined,
    passingScore: undefined,
    scoreLine: undefined,
    singleChoiceNum: undefined,
    multipleChoiceNum: undefined,
    shortAnswerNum: undefined,
    essayNum: undefined,
    trueFalseNum: undefined,
    singleChoiceScore: undefined,
    multipleChoiceScore: undefined,
    multipleChoicePartialScore: undefined,
    shortAnswerScore: undefined,
    essayScore: undefined,
    trueFalseScore: undefined,
    singleChoiceTotalScore: undefined,
    multipleChoiceTotalScore: undefined,
    shortAnswerTotalScore: undefined,
    essayTotalScore: undefined,
    trueFalseTotalScore: undefined,
    questionType: undefined,
    questionTypeConfig: undefined,
  }
  formRef.value?.resetFields()
}

function receiveDataFromPaperList(data) {
  formData.value = data[0]
  formData.value.examName = data[0].paperName
  formData.value.paperId = data[0].id
  formData.value.id = id.value;
}
</script>
